package test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.io.Files;
import com.sun.deploy.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by urfresh.mark on 2017/5/22.
 */
public class JsonFormat {

    public static void main(String[] args) throws Exception {

        FileInputStream inputStream = null;
        Scanner sc = null;
        List<String> list = new ArrayList<>();
        int start = 0;
        int count = 0;
        File newFile1 = new File("C:\\Users\\urfresh.mark\\Desktop\\log\\0521_new.log");
        try {
            inputStream = new FileInputStream("C:\\Users\\urfresh.mark\\Desktop\\log\\0521.log");
            sc = new Scanner(inputStream, "UTF-8");
            AtomicInteger c = new AtomicInteger();
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                JSONObject obj = JSON.parseObject(line);
                obj.put("createTime", obj.getString("submitTime"));

                list.add(obj.toJSONString());
                if(list.size()>=50){
                    count+=list.size();
                    if(start>count) {
                        list.clear();
                        continue;
                    }
                    Files.append(StringUtils.join(list,"\n"), newFile1, Charset.forName("utf-8"));
                    System.out.println("已执行数量："+(c.addAndGet(list.size())));
                    list.clear();
                }
//                Files.append(obj.toJSONString()+"\n", newFile1, Charset.forName("utf-8"));
//                System.out.println(count++);
            }
            if (sc.ioException() != null) {
                throw sc.ioException();
            }
        } finally {
            if(list!=null && list.size()>0)
                Files.append(StringUtils.join(list,"\n"), newFile1, Charset.forName("utf-8"));

            if (inputStream != null) {
                inputStream.close();
            }
            if (sc != null) {
                sc.close();
            }
        }

    }
}
